import { getConnection, isDatabaseConnected } from '../config/database.js';
import fs from 'fs/promises';
import path from 'path';

export interface AppConfig {
  aiConfig?: {
    provider: string;
    apiKey: string;
    model: string;
  };
  customPrompts?: {
    simple?: string;
    professional?: string;
  };
  [key: string]: any;
}

const CONFIG_FILE = path.join(process.cwd(), 'data', 'config.json');

/**
 * 数据库配置服务类
 */
export class DatabaseConfigService {
  /**
   * 保存配置
   */
  static async saveConfig(key: string, value: any): Promise<void> {
    if (isDatabaseConnected()) {
      await this.saveToDatabase(key, value);
    } else {
      await this.saveToFile(key, value);
    }
  }

  /**
   * 获取配置
   */
  static async getConfig(key: string): Promise<any> {
    if (isDatabaseConnected()) {
      return await this.getFromDatabase(key);
    } else {
      return await this.getFromFile(key);
    }
  }

  /**
   * 获取所有配置
   */
  static async getAllConfig(): Promise<AppConfig> {
    const dbConnected = isDatabaseConnected();
    
    console.log('🔧 DatabaseConfigService.getAllConfig - 数据库连接状态:', dbConnected);
    
    if (dbConnected) {
      console.log('📊 使用数据库读取配置');
      const result = await this.getAllFromDatabase();
      console.log('📊 数据库读取结果:', JSON.stringify(result, null, 2));
      return result;
    } else {
      console.log('📁 使用文件读取配置');
      const result = await this.getAllFromFile();
      console.log('📁 文件读取结果:', JSON.stringify(result, null, 2));
      return result;
    }
  }

  /**
   * 删除配置
   */
  static async deleteConfig(key: string): Promise<void> {
    if (isDatabaseConnected()) {
      await this.deleteFromDatabase(key);
    } else {
      await this.deleteFromFile(key);
    }
  }

  // 数据库操作方法
  private static async saveToDatabase(key: string, value: any): Promise<void> {
    const connection = getConnection();
    if (!connection) throw new Error('数据库未连接');

    const sql = `
      INSERT INTO app_config (config_key, config_value) 
      VALUES (?, ?) 
      ON DUPLICATE KEY UPDATE 
      config_value = VALUES(config_value), 
      updated_at = CURRENT_TIMESTAMP
    `;
    
    await connection.execute(sql, [key, JSON.stringify(value)]);
  }

  private static async getFromDatabase(key: string): Promise<any> {
    const connection = getConnection();
    if (!connection) throw new Error('数据库未连接');

    const sql = 'SELECT config_value FROM app_config WHERE config_key = ?';
    const [rows] = await connection.execute(sql, [key]) as any;
    
    if (rows.length > 0) {
      try {
        // 安全解析JSON
        if (typeof rows[0].config_value === 'string') {
          // 检查是否为空字符串
          if (rows[0].config_value.trim() === '') {
            return null;
          }
          return JSON.parse(rows[0].config_value);
        } else if (rows[0].config_value !== null && rows[0].config_value !== undefined) {
          return rows[0].config_value;
        } else {
          return null;
        }
      } catch (error) {
        console.warn(`解析配置项 ${key} 失败:`, error, '原始值:', rows[0].config_value);
        return null;
      }
    }
    return null;
  }

  private static async getAllFromDatabase(): Promise<AppConfig> {
    console.log('🔍 开始从数据库读取配置...');
    const connection = getConnection();
    if (!connection) throw new Error('数据库未连接');
    console.log('✅ 数据库连接获取成功');

    const sql = 'SELECT config_key, config_value FROM app_config';
    const [rows] = await connection.execute(sql) as any;
    console.log('📊 数据库查询结果行数:', rows.length);
    console.log('📊 数据库原始数据:', JSON.stringify(rows, null, 2));
    
    const config: AppConfig = {};
    for (const row of rows) {
      try {
        console.log(`🔧 处理配置项: ${row.config_key} = ${row.config_value}`);
        // 安全解析JSON，处理可能的解析错误
        if (typeof row.config_value === 'string') {
          // 检查是否为空字符串
          if (row.config_value.trim() === '') {
            config[row.config_key] = null;
            continue;
          }
          
          // 尝试JSON解析，如果失败则保持原始字符串值
          try {
            config[row.config_key] = JSON.parse(row.config_value);
            console.log(`✅ JSON解析成功: ${row.config_key}`);
          } catch (parseError) {
            // 如果JSON解析失败，说明这是一个普通字符串值
            config[row.config_key] = row.config_value;
            console.log(`📝 保持字符串值: ${row.config_key} = ${row.config_value}`);
          }
        } else if (row.config_value !== null && row.config_value !== undefined) {
          // 如果已经是对象，直接使用
          config[row.config_key] = row.config_value;
        } else {
          config[row.config_key] = null;
        }
      } catch (error) {
        console.warn(`❌ 处理配置项 ${row.config_key} 失败:`, error, '原始值:', row.config_value);
        // 跳过无法处理的配置项
        continue;
      }
    }
    console.log('🎯 最终数据库配置对象:', JSON.stringify(config, null, 2));
    return config;
  }

  private static async deleteFromDatabase(key: string): Promise<void> {
    const connection = getConnection();
    if (!connection) throw new Error('数据库未连接');

    const sql = 'DELETE FROM app_config WHERE config_key = ?';
    await connection.execute(sql, [key]);
  }

  // 文件操作方法
  private static async saveToFile(key: string, value: any): Promise<void> {
    try {
      let config: AppConfig = {};
      
      try {
        const data = await fs.readFile(CONFIG_FILE, 'utf-8');
        config = JSON.parse(data);
      } catch (error) {
        // 文件不存在或格式错误，使用空配置
      }
      
      config[key] = value;
      
      // 确保目录存在
      await fs.mkdir(path.dirname(CONFIG_FILE), { recursive: true });
      await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
    } catch (error) {
      console.error('保存配置到文件失败:', error);
      throw error;
    }
  }

  private static async getFromFile(key: string): Promise<any> {
    try {
      const data = await fs.readFile(CONFIG_FILE, 'utf-8');
      const config = JSON.parse(data);
      return config[key] || null;
    } catch (error) {
      return null;
    }
  }

  private static async getAllFromFile(): Promise<AppConfig> {
    try {
      const data = await fs.readFile(CONFIG_FILE, 'utf-8');
      return JSON.parse(data);
    } catch (error) {
      return {};
    }
  }

  private static async deleteFromFile(key: string): Promise<void> {
    try {
      const data = await fs.readFile(CONFIG_FILE, 'utf-8');
      const config = JSON.parse(data);
      delete config[key];
      await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
    } catch (error) {
      // 文件不存在或其他错误，忽略
    }
  }
}